<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
/*
Copyright (c) 2010 Luis Sánchez Castellanos (http://iquark.org)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of copyright holders nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * YalsciLib Class
 *
 * @package	CodeIgniter
 * @subpackage	Libraries
 * @category	Sign in/up
 * @author      QuarK
 * @link	http://iquark.org/yalsci
 */

class YalsciLib
{
    /**
     * Constructor
     *
     * @access	public
     */
    function YalsciLib()
    {
    }

    /**
     * Check the sign in of an user
     *
     * @access public
     * @param string
     * @param string
     * @return array
     */
    function checkSignIn($user, $password)
    {
        $return = array();
        $CI=&get_instance();
        $CI->config->load('yalsci');
		$CI->load->model('yalsci_model');
        $usersTableName = $CI->config->item('usersTableName');
        $useEmailAsUser = $CI->config->item('useEmailAsUser');
		$email_attribute = $CI->config->item('email_attribute');
		$username_attribute = $CI->config->item('username_attribute');
		$password_attribute = $CI->config->item('password_attribute');
		$user_id_attribute = $CI->config->item('user_id_attribute');
		$name_attribute = $CI->config->item('name_attribute');
		$lastname_attribute = $CI->config->item('lastname_attribute');
		$activationOnRegister = $CI->config->item('activationOnRegister');
		$inactiveTableName = $CI->config->item('inactiveTableName');
		
		$CI->load->database();
		/* @todo make the users' table
		 * Wherever the table for the users, it has to have
		 * the following columns:
		 *  - name
		 *  - lastname
		 *  - user_id
		 *  - email
		 *  - password
		 * But you could change that below :D
		*/
		$query = $CI->yalsci_model->getUserDataByUserPassword($user, $password);
		if(!isSet($query) || $query=="" || $query->num_rows()==0)
		{ 
			$return['user_id'] = -2;
			$return['name'] = "";
			$return['lastname'] = "";
		}
		else 
		{
			$resarray = $query->result_array();
			$return['user_id'] = $resarray[0][$user_id_attribute];
			$return['name'] = $resarray[0][$name_attribute];
			$return['lastname'] = $resarray[0][$lastname_attribute];
			// if 'activation on register' is active, we check is an activated user
			if($activationOnRegister==TRUE) {
				if($CI->yalsci_model->isInactive($return['user_id'])) {
					$return['user_id'] = -3;
					$return['name'] = "";
					$return['lastname'] = "";
				}
			}
		}

        return $return;
    }
    
    /**
     * Check the admin's sign in
     *
     * @access public
     * @param string
     * @param string
     * @return array
     */
    function checkAdminSignIn($user, $password)
    {
        $return = array();
        $CI=&get_instance();
        $CI->config->load('yalsci');
		// is the admin
		if($user == $CI->config->item('user') 
           && $password == $CI->config->item('password')) {
			$return['user_id'] = -1;
			$return['name'] = $CI->config->item('admin_name');
			$return['lastname'] = $CI->config->item('admin_lastname');
		}
		
		return $return;
    }
    /**
     * 
     * 
     * 
     **/
    function register($email, $password, $user=NULL) {
		$return['registered'] = true;
        $CI=&get_instance();
        $CI->config->load('yalsci');
        // load all variables we need from yalsci's configuration file
		$usersTableName = $CI->config->item('usersTableName');
		$email_attribute = $CI->config->item('email_attribute');
		$password_attribute = $CI->config->item('password_attribute');
		$username_attribute = $CI->config->item('username_attribute');
		$date_creation_attribute = $CI->config->item('date_creation_attribute');
		$date_modification_attribute = $CI->config->item('date_modification_attribute');
		$activationOnRegister = $CI->config->item('activationOnRegister');
		$useEmailAsUser = $CI->config->item('useEmailAsUser');
		$user_id_attribute = $CI->config->item('user_id_attribute');
		$email_attribute = $CI->config->item('email_attribute');
		$activation_key_attribute = $CI->config->item('activation_key_attribute');
		$inactiveTableName = $CI->config->item('inactiveTableName');
		
		// trying to store the user information
		$data = array(
			"$email_attribute" => $email,
			"$password_attribute" => $password,
			"$date_creation_attribute" => strtotime(time()),
			"$date_modification_attribute" => strtotime(time())
		);
		if($useEmailAsUser==FALSE)
		{
			$data["$username_attribute"] = $user;
		}
		try {
			$insert = $CI->db->insert($usersTableName, $data);
			if($insert!=null){
				$data['error']=$CI->db->_error_message();
				if($activationOnRegister==TRUE) {
					// get the user id for send him an activation email
					$CI->db->select($user_id_attribute)->from($usersTableName)->where($email_attribute, $email);
					$query = $CI->db->get();
					$query_array = $query->row_array();
					$CI->load->library('yalsciLib');
					$key = $CI->yalscilib->sendActivationEmail($email);
					// storing into activation's table
					$data = array(
						"$user_id_attribute" => $query_array[$user_id_attribute],
						"$activation_key_attribute" => $key
					);
					try {
						$CI->db->insert($inactiveTableName, $data);
					} catch(Exception $exc) {
						$return['error']=$exc;
					}
				}
			} else {
				$return['error']=$CI->db->_error_message();
				$return['registered'] = false;
			}
		} catch (Exception $exc) {
			$return['registered'] = false;
		}

		return $return;
    }
    /**
     * Creates a new password, code written by bjornbjorn (http://www.twitter.com/bjornbjorn).
     *
     * get_random_password() will return a random password with length 6-8 of lowercase letters only.
     *
     * @access    public
     * @param    $chars_min the minimum length of password (optional, default 6)
     * @param    $chars_max the maximum length of password (optional, default 8)
     * @param    $use_upper_case boolean use upper case for letters, means stronger password (optional, default false)
     * @param    $include_numbers boolean include numbers, means stronger password (optional, default false)
     * @param    $include_special_chars include special characters, means stronger password (optional, default false)
     *
     * @return    string containing a random password 
     */
    function _createRandomPassword($chars_min=6, $chars_max=8, $use_upper_case=false, $include_numbers=false, $include_special_chars=false)
    {
        $length = rand($chars_min, $chars_max);
        $selection = 'aeuoyibcdfghjklmnpqrstvwxz';
        if($include_numbers) {
            $selection .= "1234567890";
        }
        if($include_special_chars) {
            $selection .= "!@\"#$%&[]{}?|";
        }
                                
        $password = "";
        for($i=0; $i<$length; $i++) {
            $current_letter = $use_upper_case ? (rand(0,1) ? strtoupper($selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))];            
            $password .=  $current_letter;
        }
        
        return $password;
    }
    /*
     * 
     *
     */
     
     function activate($key) 
	 {
		$CI=&get_instance();
		if($CI->yalscimodel->activateUser($key)) 
		{
			$return = true;
		}
		else
		{
			$return = false;
		}
		
		return $return;
     }
    /*
     * Sends an email with a generated password 
     * 
     */
    function sendForgotEmail($email)
    {
        $CI=&get_instance();
		// prueba de envio de correo
		$message = $CI->lang->line('email_reset_password');
		$subject = $CI->lang->line('email_reset_password_subject');
		$password = $this->_createRandomPassword();
		$message = str_replace('{password}', $password, $message);
		$this->_sendEmail($email, $subject, $message);
    }
    /*
    * Sends an email to activate an account 
    * 
    */
    function sendActivationEmail($email)
    {
		$CI=&get_instance();
		$CI->load->helper('url');
		$CI->load->library('encrypt');
		// test of email sending
		$message = $CI->lang->line('email_activation');
		$subject = $CI->lang->line('email_activation_subject');
		$password = $this->_createRandomPassword();
		$hash = $CI->encrypt->sha1("{$email}{$password}");
		$str =  site_url("user/activate/".$hash);
		$message = str_replace('{url}', $str, $message);
		
		return $hash;
    }
    /*
     * Sends an email
     */
    function _sendEmail($email, $subject, $message)
    {
		$CI=&get_instance();
        $CI->config->load('yalsci');
		$config['protocol'] = 'sendmail';
		$config['mailpath'] = '/usr/sbin/sendmail';
		$config['wordwrap'] = TRUE;
		$fromAddress = $CI->lang->line('email_from_address');
		$fromName = $CI->lang->line('email_from_name');
		
		$CI->load->library('email');
		$CI->email->initialize($config);
		$CI->email->from($fromAddress, $fromName);
		$CI->email->to($email); 

		$CI->email->subject($subject);
		$CI->email->message($message);	

		$CI->email->send();

		echo $CI->email->print_debugger();
    }
}

// END YalsciLib Class
/* End of file YalsciLib.php */
/* Location: ./system/application/libraries/YalsciLib.php */
